<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
use Cart;
use DB;
use Hash;

class OrderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */


    public function index()
    {   
        //$res = DB::table('address')->where(['uid'=>$uid,'status'=>1])->first();
        
        //购物车信息
        $uid = Auth::user()->id;
        $cart = Cart::instance($uid)->content();
        //用户地址信息
        $add = DB::table('address')->where(['uid'=>$uid,'status'=>1])->first();
        if(!$add){
            return redirect('address');
        }
        //echo '<pre>';
       //dd($cart);
        $pay = Cart::instance($uid)->subtotal(); 
       return view('home.pay')->with('cart',$cart)->with('pay',$pay)->with('add',$add);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
       //dd($request);
       // 存入退货商品表
       $data = $request->except('_token');
       //退货时间
       $time = time();
       $data['refund_time'] = $time;
       // print_r($data);
       // die;
       //存入表
       $refundStatus = DB::table('order')->where(['id'=>$data['order_id'],
                                                  'goods_id'=>$data['goods_id']
                                                  ])
                                         ->update(['refund'=>1]);
        if($refundStatus){
             $res = DB::table('refund')->insert($data);
         }
         //dd($res);
        return redirect('refundList');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //展示退货页面
        //获取申请退款商品信息
        $orderInfo = DB::table('order')
                            ->where('id',$id)
                            ->join('goods','order.goods_id','=','goods.goods_id')
                            ->select('order.*','goods.*')
                            ->first();
        //dd($orderInfo);
        //确认退款状态 
        if($orderInfo->refund !== 0){
            return redirect('orderInfo');
        }

        return view('home.refund')->with('orderInfo',$orderInfo);


    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function createOrder($add_id)
    {
        $uid = Auth::user()->id;
        $res = DB::table('address')->where(['uid'=>$uid,'status'=>1])->first();
        if(!$res){
            return redirect('address');
        }

         //获取用户信息
        $user = Auth::user();
        //dd($user);
        $uid = $user->id;
        //获取购物车信息
        $cart = Cart::instance($uid)->content();
        //获取付款总金额
        $pay = Cart::instance($uid)->subtotal();

        //获取下单时间
        $time = time();
        //生成订单号
        $order_num = substr($time,-4).rand(10000,99999);
        //dd($order_num);
        foreach($cart as $v){
            //商品id
            $gid  = $v->id;
            //商品数量
            $g_num = $v->qty;
            //商品总价格
            $total = ($v->qty)*($v->price);
            //商品款式
            $style =$v->options->size.$v->options->color;
            // echo $total;
            // die;
            //商家id
            $shop = DB::table('goods')->where('goods_id',$gid)->first();
            $sid = $shop->shop_id;
             $data = [] ;
             $data['order_num'] = $order_num;
             $data['uid'] = $uid;
             $data['shop_id'] = $sid;
             $data['order_time'] = $time;
             $data['goods_id'] = $gid;
             $data['goods_num'] = $g_num;
             $data['total_pay'] = $total;
             $data['address_id'] = $add_id;
             $data['style'] = $style;
             $data['order_status']  = 4 ;
            // $data['status'] = 1;
             //dd($data); 
            //存入订单主表

            $res = DB::table('order')->insert($data);
           // print_r($res);
           

        }
        Cart::instance($uid)->destroy();
        return view('home.pay_confirm')->with('order_num',$order_num);
    }

    public function showOrder()
    {   

        //获取用户id
        $user = Auth::user();
        $uid = $user->id;
        //获取全部订单信息
        $orderInfo = DB::table('order')
                        ->where('uid',$uid)
                        ->join('goods','order.goods_id','=','goods.goods_id')
                        ->join('shop','order.shop_id','=','shop.shop_id')
                        ->select('order.*','goods.*','shop.store_name')
                        ->orderBy('order_time','desc')
                        ->get();
        //获取未付款订单
         $wait_pay = DB::table('order')
                        ->where(['uid'=>$uid,'order_status'=>4])
                        ->join('goods','order.goods_id','=','goods.goods_id')
                        ->join('shop','order.shop_id','=','shop.shop_id')
                        ->select('order.*','goods.*','shop.store_name')
                        ->orderBy('order_time','desc')
                        ->get();
        //获取未发货订单
        $order_paid= DB::table('order')
                        ->where(['uid'=>$uid,'order_status'=>0,'refund'=>0])
                        ->join('goods','order.goods_id','=','goods.goods_id')
                        ->join('shop','order.shop_id','=','shop.shop_id')
                        ->select('order.*','goods.*','shop.store_name')
                        ->orderBy('order_time','desc')
                        ->get();

        //获取未确认收货订单
        $order_send = DB::table('order')
                        ->where(['uid'=>$uid,'order_status'=>1,'refund'=>0])
                        ->join('goods','order.goods_id','=','goods.goods_id')
                        ->join('shop','order.shop_id','=','shop.shop_id')
                        ->select('order.*','goods.*','shop.store_name')
                        ->orderBy('order_time','desc')
                        ->get();

        //获取待评价订单
        $order_done = DB::table('order')
                        ->where(['uid'=>$uid,'order_status'=>2,'refund'=>0])
                        ->join('goods','order.goods_id','=','goods.goods_id')
                        ->join('shop','order.shop_id','=','shop.shop_id')
                        ->select('order.*','goods.*','shop.store_name')
                        ->orderBy('order_time','desc')
                        ->get();

        //获取
       //dd($orderInfo);
       
        $status = [];
        foreach($orderInfo as $v){
             //判断收货状态
            switch($v->order_status){
                case 0:
                $a ='买家已付款';
                break;
                case 1:
                $a = '卖家已发货';
                break;
                case 2:
                $a = '待评价';
                break;
                case 3:
                $a = '交易成功';
                break;
                case 4:
                $a = '未付款';
                break;
            }

           // var_dump($v->status);
           // echo '<br>';

            //判断是否在退货
            switch($v->refund){
                case 1:
                $a = '退款中';
                break;
                case 2:
                $a = '退款完成';
                break;
                case 3:
                $a = '退款失败';
                break;
            }
            $status[$v->id] = $a;

        }

       // dd($order_send);
        //die;
       //dd($status);
        return view('home.order')->with('orderInfo',$orderInfo)
                                 ->with('wait_pay',$wait_pay)
                                 ->with('order_paid',$order_paid)
                                 ->with('order_send',$order_send)
                                 ->with('order_done',$order_done)
                                 ->with('status',$status);
    }

    public function orderDel($order_num,$goods_id)
    {   
        //获取用户信息
        $user = Auth::user();
        $uid = $user->id;
        //dd($uid);
        //执行删除订单
        $res = DB::table('order')
                ->where([
                    'uid'=>$uid ,
                    'order_num'=>$order_num ,
                    'goods_id'=>$goods_id
                    ])
                ->delete();
        return redirect('orderInfo');
    }

    public function getGoods($goods_id,$id)
    {   

        $user = Auth::user();
        $uid = $user->id;
        //dd($uid);
        //修改订单收货状态
        $res = DB::table('order')
                ->where([
                    'uid'=>$uid ,
                    'id'=>$id ,
                    'goods_id'=>$goods_id
                    ])
                ->update(['order_status'=>2]);
        return redirect('orderInfo');
    }




    public function showRefund()
    {   
        //用户ID
        $uid = Auth::user()->id;
        //退货信息
        $refundInfo = DB::table('order')
                            ->where('uid',$uid)
                            ->whereIn('refund',[1,2,3])
                            ->join('refund','order.id','=','refund.order_id')
                            ->join('goods','order.goods_id','=','goods.goods_id')
                            ->select('goods.goods_name','goods.pic','order.order_num','order.refund','refund.id','refund.refund_time','refund.refund_money')
                            ->orderBy('refund_time','desc')
                            ->paginate(10);

        //转换退货状态
        $status = [] ;
        foreach($refundInfo as $v){
             switch($v->refund){
                case 1:
                $a = '退款中';
                break;
                case 2:
                $a = '退款完成';
                break;
                case 3:
                $a = '退款失败';
                break;
            }
        $status[$v->id] = $a;
        }
       // dd($refundInfo);
        //dd($status);
        return view('home.refund_list')->with('refundInfo',$refundInfo)
                                       ->with('status',$status);
    }

    public function payConfirm(Request $request)
    {    
        $uid = Auth::user()->id;
        $res = DB::table('address')->where(['uid'=>$uid,'status'=>1])->first();
        //dd($res);
        if(!$res){
            return redirect('address');
        }
        //dd(1111);
        $pwd = Auth::user()->password;
        $password = $request->password;
        //dd($pwd);
        //判断密码是否为空
        if(empty($password)){
            return back()->withError('请输入密码');
        }
        //判断密码是否正确
        if(!Hash::check($password,$pwd)){
            return back()->withError('密码错误!');
           // dd($password);
        }


        //执行订单操作
        if(empty($request->goods_id)){
            $orderInfo = DB::table('order')->where('order_num',$request->order_num)
                                           ->join('goods','order.goods_id','=','goods.goods_id')
                                           ->select('order.*','goods.number')
                                           ->get();
            //循环判断商品库存
            foreach($orderInfo as $v){
                if($v->goods_num > $v->number){
                    //如果库存不足 跳转到订单列表 执行手动支付
                    return redirect('orderInfo');
                }
            }

            //修改订单状态
            $res = DB::table('order')->where('order_num',$request->order_num)->update(['order_status'=>0]); 
            //循环更新商品库存
            foreach($orderInfo as $v){
                $new_number = ($v->number)-($v->goods_num);
                $res = DB::table('goods')->where('goods_id',$v->goods_id)->update(['number'=>$new_number]);
            }
            //成功后跳转到成功页面
            return redirect("/success/{$request->order_num}");
        }else{
            $orderInfo = DB::table('order')->where(['order_num'=>$request->order_num,'order.goods_id'=>$request->goods_id])
                                           ->join('goods','order.goods_id','=','goods.goods_id')
                                           ->select('order.*','goods.number')
                                           ->first();
            if($orderInfo->goods_num > $orderInfo->number){
                    //如果库存不足 提示错误信息
                    return back()->with('error','库存不足,支付失败!');
            }
            //修改订单状态
            $res = DB::table('order')->where(['order_num'=>$request->order_num,'goods_id'=>$request->goods_id])->update(['order_status'=>0]);                          
            //更新商品库存
            $new_number = ($orderInfo->number)-($orderInfo->goods_num);
            $res = DB::table('goods')->where('goods_id',$orderInfo->goods_id)->update(['number'=>$new_number]);
            //成功后跳转到成功页面
            return redirect("/success/{$request->order_num}/{$request->goods_id}");
        }

    }

    public function successPay($order_num,$goods_id=0)
    {
        if($goods_id == 0){
            $orderInfo = DB::table('order')->where('order_num',$order_num)
                                           ->join('address','order.address_id','=','address.id')
                                           ->select('order.*','address.*')
                                           ->get();
            foreach($orderInfo as $v){
                $address = $v->address;
                $name = $v->name;
                $phone = $v->phone;
            }

        
            // $address = $orderInfo[0]->address;
            //  //dd($address);
            // $name = $orderInfo[0]->name;
            // $phone = $orderInfo[0]->phone;
            //dd($orderInfo);
            $pay = 0 ;
            foreach($orderInfo as $v){
                $pay += $v->total_pay;
            }
            return view('home.success_pay')->with('address',$address)
                                           ->with('name',$name)
                                           ->with('phone',$phone)
                                           ->with('pay',$pay);
        }else{
            $orderInfo = DB::table('order')->where(['order_num'=>$order_num,'goods_id'=>$goods_id])
                                           ->join('address','order.address_id','=','address.id')
                                           ->select('order.*','address.*')
                                           ->first();
            $address = $orderInfo->address;
            $name = $orderInfo->name;
            $phone = $orderInfo->phone;
            $pay = $orderInfo->total_pay;
            return view('home.success_pay')->with('address',$address)
                                           ->with('name',$name)
                                           ->with('phone',$phone)
                                           ->with('pay',$pay);
        }
    }

    public function doPay($order_num,$goods_id)
    {
        return view('home.pay_confirm')->with('order_num',$order_num)->with('goods_id',$goods_id);
    }
}

